package poli.tidia.mobile.proxy;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import poli.tidia.mobile.model.Site;
import poli.tidia.mobile.model.SiteMenuItem;

public class SiteCollectionProxy {

	public List<SiteMenuItem> getMySites()
	{
		List<SiteMenuItem> result = new ArrayList<SiteMenuItem>();
		
		RestClient client = RestClient.getInstance("http://agora.tidia-ae.usp.br/portal/");
        
        try {
            client.Execute(RestClient.RequestMethod.POST);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String response = client.getResponse();
        Document doc = Jsoup.parse(response);
        Elements tableRows = doc.select("div#linkNav ul#siteLinkList a");
        
        for (Element e : tableRows) {
			if (!e.text().trim().equals("Site Unavailable")) {
				result.add(new SiteMenuItem(e.attr("href"), e.text()));
			}
    	}
        
		return result;
	}
	public Site selectSite(String siteUrl)
	{
		Site result = null;
		RestClient client = RestClient.getInstance(siteUrl);
        
        try {
            client.Execute(RestClient.RequestMethod.POST);
            
            String response = client.getResponse();
            Document doc = Jsoup.parse(response);

            Elements menuItems = doc.select("#toolMenu").first().children();
            
            result = new Site();    
    		result.setSiteId(siteUrl.substring(siteUrl.lastIndexOf('/')));
    		result.setName(doc.title().substring(doc.title().indexOf(" : "), doc.title().lastIndexOf(" : ")));
    		result.setResourcesUrl(menuItems.select("a[class=icon-sakai-resources]").attr("href"));
    		result.setAnnouncementsUrl(menuItems.select("a[class=icon-sakai-announcements]").attr("href"));
    		result.setDiscussionBoardUrl(menuItems.select("a[class=icon-sakai-forums]").attr("href"));
    		
    		
        } catch (Exception e) {
            e.printStackTrace();
        }
    	
		return result;
	}
}
